package com.mumu.xiaodu

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.*
import android.os.Handler
import android.os.Looper

data class HistoryItem(
    val title: String,
    val url: String,
    val timestamp: Long,
    val id: Long = System.currentTimeMillis()
)

class HistoryManager(private val context: Context) {
    
    private val prefs: SharedPreferences = context.getSharedPreferences("history", Context.MODE_PRIVATE)
    private val gson = Gson()
    private val maxHistorySize = 1000 // 最大历史记录数量
    
    // 🚀 后台线程处理器，避免 StrictMode 违规
    private val backgroundHandler = Handler(Looper.getMainLooper())
    private val historyScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    fun getAllHistory(): List<HistoryItem> {
        val json = prefs.getString("history_list", "[]")
        val type = object : TypeToken<List<HistoryItem>>() {}.type
        val history: List<HistoryItem> = gson.fromJson(json, type) ?: emptyList()
        return history.sortedByDescending { it.timestamp }
    }
    
    // 🚀 异步添加历史记录，避免主线程磁盘操作
    fun addHistory(historyItem: HistoryItem) {
        historyScope.launch {
            try {
                val history = withContext(Dispatchers.IO) {
                    getAllHistory().toMutableList()
                }
                
                // 移除相同URL的旧记录
                history.removeAll { it.url == historyItem.url }
                
                // 添加新记录到开头
                history.add(0, historyItem)
                
                // 限制历史记录数量
                if (history.size > maxHistorySize) {
                    history.subList(maxHistorySize, history.size).clear()
                }
                
                // 🚀 在后台线程保存，避免 StrictMode 违规
                withContext(Dispatchers.IO) {
                    saveHistory(history)
                }
            } catch (e: Exception) {
                // 静默处理错误，避免影响用户体验
                android.util.Log.w("HistoryManager", "Failed to save history: ${e.message}")
            }
        }
    }
    
    // 🚀 异步删除历史记录
    fun removeHistory(historyId: Long) {
        historyScope.launch {
            try {
                val history = withContext(Dispatchers.IO) {
                    getAllHistory().toMutableList()
                }
                history.removeAll { it.id == historyId }
                
                withContext(Dispatchers.IO) {
                    saveHistory(history)
                }
            } catch (e: Exception) {
                android.util.Log.w("HistoryManager", "Failed to remove history: ${e.message}")
            }
        }
    }

    fun clearAllHistory() {
        historyScope.launch {
            withContext(Dispatchers.IO) {
                prefs.edit().remove("history_list").apply()
            }
        }
    }

    fun searchHistory(query: String): List<HistoryItem> {
        val history = getAllHistory()
        return history.filter { 
            it.title.contains(query, ignoreCase = true) || 
            it.url.contains(query, ignoreCase = true) 
        }
    }

    fun getHistoryByDate(startTime: Long, endTime: Long): List<HistoryItem> {
        val history = getAllHistory()
        return history.filter { it.timestamp in startTime..endTime }
    }

    fun getLastVisited(): HistoryItem? {
        val history = getAllHistory()
        return history.firstOrNull()
    }

    fun getFrequentlyVisited(limit: Int = 10): List<HistoryItem> {
        val history = getAllHistory()
        val urlGroups = history.groupBy { it.url }
        
        return urlGroups.values
            .sortedByDescending { it.size }
            .take(limit)
            .map { it.first() }
    }

    private fun saveHistory(history: List<HistoryItem>) {
        val json = gson.toJson(history)
        prefs.edit().putString("history_list", json).apply()
    }
    
    // 🧹 清理资源
    fun cleanup() {
        historyScope.cancel()
    }
} 